package com.uwo.house.controller;

import com.uwo.house.kits.CacheKits;
import com.uwo.house.kits.SmsKits;
import com.uwo.house.service.serviceImpl.UserService;
import com.uwo.house.util.UtilReturn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by yanhao on 2017/7/22.
 */
@Controller
public class ToolController {

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping(value = "/sms", method = RequestMethod.POST)
    public Object sms(@RequestParam(value = "mobile") String mobile) {
        try {
            int code = (int) ((Math.random() * 9 + 1) * 100000);
            String content = String.format("尊敬的用户您好，您的验证码为%d。【懒汉工坊】", code);
            CacheKits.put(String.valueOf(code), mobile);
            return SmsKits.send(content, mobile);
        } catch (Exception e) {
            return "{'code':'503'}";
        }
    }

    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Object register(@RequestParam(value = "mobile") String mobile,
                           @RequestParam(value = "password") String password,
                           @RequestParam(value = "sms") String sms) {
        if (!CacheKits.has(sms))
            return UtilReturn.resErrorMap("验证码错误！", UtilReturn.ERROR_CODE);
        String smsMobile = (String) CacheKits.get(sms);
        if (!mobile.equalsIgnoreCase(smsMobile))
            return UtilReturn.resErrorMap("验证码错误！", UtilReturn.ERROR_CODE);

        if (!userService.register(mobile, password))
            return UtilReturn.resErrorMap("注册失败！", UtilReturn.ERROR_CODE);
        return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, "注册成功");
    }

}
